package task

import (
	"io"
	"path"
	"time"

	"github.com/PuerkitoBio/goquery"
)

type UserContestHistoryTask struct {
	TaskBase
}

type userContestInfo struct {
	ContestName  string
	ContestId    string
	StartTime    int64
	Rank         string
	Solved       string
	RatingChange string
	NewRating    string
	MoreInfo     string
}

func (u *UserContestHistoryTask) GetParseFunc(r io.Reader) interface{} {
	doc, e := goquery.NewDocumentFromReader(r)
	if e != nil {
		u.SetErr(e)
		return ""
	}
	trs := doc.Find(".datatable").Find("tbody").Find("tr")
	contestHis := make([]userContestInfo, 0, 128)
	for i := 0; i < trs.Length(); i++ {
		t := userContestInfo{}

		ti, _ := time.Parse("Jan/02/2006 15:04", trim(trs.Eq(i).Find("td").Eq(2).Find("span").Text()))
		t.ContestName = trim(trs.Eq(i).Find("td").Eq(1).Text())
		t.ContestId = path.Base(trs.Eq(i).Find("td").Eq(1).Find("a").AttrOr("href", "/-1"))
		t.StartTime = ti.UnixMilli()
		t.Rank = trim(trs.Eq(i).Find("td").Eq(3).Text())
		t.Solved = trim(trs.Eq(i).Find("td").Eq(4).Find("a").Text())
		t.RatingChange = trim(trs.Eq(i).Find("td").Eq(5).Find("span").Text())
		t.NewRating = trim(trs.Eq(i).Find("td").Eq(6).Text())
		t.MoreInfo = trim(trs.Eq(i).Find("td").Eq(7).Text())
		contestHis = append(contestHis, t)
	}
	return contestHis

}

func NewUserContestHistoryTask(name string) ITask {
	return &UserContestHistoryTask{
		TaskBase{
			url: "https://codeforces.com/contests/with/" + name,
		},
	}
}
